package com.aimaterials.resource.controller;

import java.util.Iterator;
import java.util.List;

import com.aimaterials.common.core.domain.entity.SysUser;
import com.aimaterials.common.core.domain.model.LoginUser;
import com.aimaterials.common.utils.ServletUtils;
import com.aimaterials.framework.web.service.TokenService;
import com.aimaterials.resource.domain.ComSpecialty;
import com.aimaterials.resource.service.IComSpecialtytService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.aimaterials.common.annotation.Log;
import com.aimaterials.common.constant.UserConstants;
import com.aimaterials.common.core.controller.BaseController;
import com.aimaterials.common.core.domain.AjaxResult;
import com.aimaterials.common.enums.BusinessType;
import com.aimaterials.common.utils.SecurityUtils;
import com.aimaterials.common.utils.StringUtils;

/**
 * 专业信息
 *
 * @author DaemonSu
 */
@RestController
@RequestMapping("/common/specialty")
public class ComSpecialtyController extends BaseController
{
    @Autowired
    private IComSpecialtytService specialtyservice;

    @Autowired
    private TokenService tokenService;

    /**
     * 获取专业列表
     */
    @PreAuthorize("@ss.hasPermi('common:specialty:list')")
    @GetMapping("/list")
    public AjaxResult list(ComSpecialty specialty)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        specialty.setSchoolId(user.getDeptId());
        List<ComSpecialty> specialtys = specialtyservice.selectDeptList(specialty);
        return AjaxResult.success(specialtys);
    }

    /**
     * 查询专业列表（排除节点）
     */
    @PreAuthorize("@ss.hasPermi('common:specialty:list')")
    @GetMapping("/list/exclude/{specialtyId}")
    public AjaxResult excludeChild(@PathVariable(value = "specialtyId", required = false) Long specialtyId)
    {
        List<ComSpecialty> specialtys = specialtyservice.selectDeptList(new ComSpecialty());
        Iterator<ComSpecialty> it = specialtys.iterator();
        while (it.hasNext())
        {
            ComSpecialty d = (ComSpecialty) it.next();
            if (d.getSpecialtyId().intValue() == specialtyId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), specialtyId + ""))
            {
                it.remove();
            }
        }
        return AjaxResult.success(specialtys);
    }

    /**
     * 根据专业编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('common:specialty:query')")
    @GetMapping(value = "/{specialtyId}")
    public AjaxResult getInfo(@PathVariable Long specialtyId)
    {
        return AjaxResult.success(specialtyservice.selectDeptById(specialtyId));
    }

    /**
     * 获取专业下拉树列表
     */
    @GetMapping("/treeselect")
    public AjaxResult treeselect(ComSpecialty specialty)
    {
        List<ComSpecialty> specialtys = specialtyservice.selectDeptList(specialty);
        return AjaxResult.success(specialtyservice.buildDeptTreeSelect(specialtys));
    }

    /**
     * 加载对应角色专业列表树
     */
    @GetMapping(value = "/roleDeptTreeselect/{roleId}")
    public AjaxResult roleDeptTreeselect(@PathVariable("roleId") Long roleId)
    {
        List<ComSpecialty> specialtys = specialtyservice.selectDeptList(new ComSpecialty());
        AjaxResult ajax = AjaxResult.success();
        ajax.put("checkedKeys", specialtyservice.selectDeptListByRoleId(roleId));
        ajax.put("specialtys", specialtyservice.buildDeptTreeSelect(specialtys));
        return ajax;
    }

    /**
     * 新增专业
     */
    @PreAuthorize("@ss.hasPermi('common:specialty:add')")
    @Log(title = "专业管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody ComSpecialty specialty)
    {
        if (UserConstants.NOT_UNIQUE.equals(specialtyservice.checkDeptNameUnique(specialty)))
        {
            return AjaxResult.error("新增专业'" + specialty.getSpecialtyName() + "'失败，专业名称已存在");
        }
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        specialty.setSchoolId(user.getDeptId());
        specialty.setCreateBy(SecurityUtils.getUsername());
        return toAjax(specialtyservice.insertDept(specialty));
    }

    /**
     * 修改专业
     */
    @PreAuthorize("@ss.hasPermi('common:specialty:edit')")
    @Log(title = "专业管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody ComSpecialty specialty)
    {
        if (UserConstants.NOT_UNIQUE.equals(specialtyservice.checkDeptNameUnique(specialty)))
        {
            return AjaxResult.error("修改专业'" + specialty.getSpecialtyName() + "'失败，专业名称已存在");
        }
        else if (specialty.getParentId().equals(specialty.getSpecialtyId()))
        {
            return AjaxResult.error("修改专业'" + specialty.getSpecialtyName() + "'失败，上级专业不能是自己");
        }
        else if (StringUtils.equals(UserConstants.DEPT_DISABLE, specialty.getStatus())
                && specialtyservice.selectNormalChildrenDeptById(specialty.getSpecialtyId()) > 0)
        {
            return AjaxResult.error("该专业包含未停用的子专业！");
        }
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        specialty.setSchoolId(user.getDeptId());
        specialty.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(specialtyservice.updateDept(specialty));
    }

    /**
     * 删除专业
     */
    @PreAuthorize("@ss.hasPermi('common:specialty:remove')")
    @Log(title = "专业管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{specialtyId}")
    public AjaxResult remove(@PathVariable Long specialtyId)
    {
        if (specialtyservice.hasChildByDeptId(specialtyId))
        {
            return AjaxResult.error("存在下级专业,不允许删除");
        }
        if (specialtyservice.checkDeptExistUser(specialtyId))
        {
            return AjaxResult.error("专业存在用户,不允许删除");
        }
        return toAjax(specialtyservice.deleteDeptById(specialtyId));
    }
}
